package com.hu.green.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hu.green.commen.R;
import com.hu.green.entity.WenxinEntity;
import com.hu.green.utils.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
@Slf4j
@RestController
@RequestMapping("/chat")
@CrossOrigin(value = "*")
public class WenXinController {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @PostMapping
    public R<WenxinEntity> chat(@RequestBody WenxinEntity wenxin) throws IOException{

        String flower1 = "请告诉我"+wenxin.getFlower()+"种植和养护方案";
        //1、访问数据
        String requestMethod = "POST";
        String body = URLEncoder.encode("junshi","UTF-8");//设置要传的信息
        //请求路径
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=24.e76a05418ec8f5ec03f33e6dda6dfe48.2592000.1700561935.282335-41545948";
        //测试：访问聚合数据的地区新闻api
        HashMap<String, String> msg = new HashMap<>();
        msg.put("role","user");
        msg.put("content", flower1);
        ArrayList<HashMap> messages = new ArrayList<>();
        messages.add(msg);
        HashMap<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", messages);
        String outputStr = JSON.toJSONString(requestBody);
        JSON json = HttpRequestUtils.httpRequest(url,requestMethod,outputStr,"application/json");

        String r = json.toJSONString();
        JSONObject jsonObject = JSON.parseObject(r);
        String r1 = jsonObject.getString("result");

        wenxin.setAdvice(r1);

        log.info(r1);
        return R.success(wenxin);
    }
}
